package com.sun.mychat.servlet;

import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController()
@RequestMapping("/img")
@Api(description = "文件操作")
public class ImgServlet {
    @ApiResponses({@ApiResponse(code = 200, message
            = "返回文件的保存后名字", response = String.class)})
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "上传的文件", dataType = "file", paramType = "query", required = true)})
    @ApiOperation(value = "文件上传接口")
    @PostMapping("/save")
    public String saveHeadImage(MultipartFile file, HttpServletRequest req) throws IllegalStateException, IOException {
        if (file.isEmpty()) {
            return "文件为空";
        }
        String path = req.getServletContext().getRealPath("/headImage");
        String fileName = file.getOriginalFilename();
        fileName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(fileName);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "") + fileName;
        File filePath = new File(path, uuid);
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        file.transferTo(filePath);
        return "headImage/" + uuid;

    }
}
